import { useState } from "react";
import BaziForm from "../../component/liujie/hehun/BaziForm"; 
import { generateBaziAnalysis } from "../../component/liujie/hehun/BaziAnalysis";
import BaziCompatibilityAnalysis from '../../component/liujie/hehun/BaziCompatibilityAnalysis';

function Index() {
    const [maleResult, setMaleResult] = useState(null);
    const [femaleResult, setFemaleResult] = useState(null);
    const [error, setError] = useState(null);
    const [aiAnalysisResult, setAIAnalysisResult] = useState(null);
    const [showDetails, setShowDetails] = useState(false);
    const [loadingAI, setLoadingAI] = useState(false);

    const handleGenerateBazi = async (name, gender, birthDate, birthTime) => {
        try {
            const result = await generateBaziAnalysis(name, gender, birthDate, birthTime);
            if (gender === "male") {
                setMaleResult(result);
            } else if (gender === "female") {
                setFemaleResult(result);
            }
            setError(null);
        } catch (error) {
            console.error("八字计算失败:", error);
            setError("八字计算失败，请检查输入信息或稍后重试。");
        }
    };

    const fetchAIAnalysis = async () => {
        if (!maleResult || !femaleResult) {
            return;
        }
        setLoadingAI(true);
        try {
            const dataToSend = { male: maleResult, female: femaleResult };
            console.log('发送给 API 的数据:', dataToSend); 
            const response = await fetch('http://localhost:5000/api/marriage-compatibility', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(dataToSend)
            });

            if (!response.ok) {
                throw new Error('API 请求失败');
            }

            const data = await response.json();
            setAIAnalysisResult(data);
        } catch (error) {
            console.error('AI 分析请求失败:', error);
        } finally {
            setLoadingAI(false);
        }
    };

    const handleShowDetails = async () => {
        if (!aiAnalysisResult) {
            await fetchAIAnalysis();
        }
        setShowDetails(true);
    };

    function parseAIAnswer(text) {
        text = text.replace(/### \*\*(.*?)\*\*/g, '<h3 style="color: #1890ff; border-bottom: 2px solid #e0e0e0; padding-bottom: 8px; margin-top: 25px;">$1</h3>');
        text = text.replace(/\*\*(.*?)\*\*/g, '<strong style="color: #333; font-weight: 600;">$1</strong>');
        text = text.replace(/^(\s*)- (.*)/gm, (match, indent, content) => {
            const level = indent.length / 2;
            const listStyle = level === 0 ? 'list-style: disc;' : 'list-style: circle; padding-left: 30px;';
            return `<li style="${listStyle}">${content}</li>`;
        });
        text = text.replace(/\n{2,}/g, '</p><p>');
        text = text.replace(/^\s*/gm, '');
        return `<p>${text}</p>`;
    }

    return (
        <div
            style={{
                padding: "20px",
                minHeight: "100vh",
                display: "flex",
                flexDirection: "column",
                alignItems: "center"
            }}
        >
            <h1 style={{ textAlign: "center", marginBottom: "30px", fontSize: "24px", fontWeight: "600" }}>专业八字命理分析</h1>
            {error && <div style={{ color: "red", marginBottom: "20px" }}>{error}</div>}

            <BaziForm onGenerateBazi={handleGenerateBazi} />

            {maleResult && maleResult.bazi && (
                <div
                    style={{
                        marginTop: "30px",
                        padding: "20px",
                        backgroundColor: "#def8ff",
                        borderRadius: "12px"
                    }}
                >
                    <h2 style={{ textAlign: "center", marginBottom: "20px", fontSize: "20px", fontWeight: "600" }}>
                        {`${maleResult.name}（男）八字命理分析报告`}
                    </h2>
                    <div style={{ fontSize: "18px", marginBottom: "15px", fontWeight: "500", textAlign: "center" }}>
                        八字：{maleResult.bazi}
                    </div>

                    <table
                        style={{
                            width: "100%",
                            borderCollapse: "collapse",
                            marginTop: "10px"
                        }}
                    >
                        <thead>
                            <tr style={{ backgroundColor: "#f0f0f0" }}>
                                <th style={{ padding: "12px", textAlign: "left", fontSize: "16px", borderBottom: "2px solid #e0e0e0" }}>
                                    分析项目
                                </th>
                                <th style={{ padding: "12px", textAlign: "left", fontSize: "16px", borderBottom: "2px solid #e0e0e0" }}>
                                    分析内容
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            {maleResult.analysis && maleResult.analysis.map((item, index) => (
                                <tr key={index} style={{ borderBottom: "1px solid #e0e0e0" }}>
                                    <td style={{ padding: "12px", fontSize: "16px", fontWeight: "500" }}>{item.title}</td>
                                    <td style={{ padding: "12px", fontSize: "16px" }}>{item.content}</td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}

            {femaleResult && femaleResult.bazi && (
                <div
                    style={{
                        marginTop: "30px",
                        padding: "20px",
                        backgroundColor: "#ffebf2",
                        borderRadius: "12px"
                    }}
                >
                    <h2 style={{ textAlign: "center", marginBottom: "20px", fontSize: "20px", fontWeight: "600" }}>
                        {`${femaleResult.name}（女）八字命理分析报告`}
                    </h2>
                    <div style={{ fontSize: "18px", marginBottom: "15px", fontWeight: "500", textAlign: "center" }}>
                        八字：{femaleResult.bazi}
                    </div>

                    <table
                        style={{
                            width: "100%",
                            borderCollapse: "collapse",
                            marginTop: "10px"
                        }}
                    >
                        <thead>
                            <tr style={{ backgroundColor: "#f0f0f0" }}>
                                <th style={{ padding: "12px", textAlign: "left", fontSize: "16px", borderBottom: "2px solid #e0e0e0" }}>
                                    分析项目
                                </th>
                                <th style={{ padding: "12px", textAlign: "left", fontSize: "16px", borderBottom: "2px solid #e0e0e0" }}>
                                    分析内容
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            {femaleResult.analysis && femaleResult.analysis.map((item, index) => (
                                <tr key={index} style={{ borderBottom: "1px solid #e0e0e0" }}>
                                    <td style={{ padding: "12px", fontSize: "16px", fontWeight: "500" }}>{item.title}</td>
                                    <td style={{ padding: "12px", fontSize: "16px" }}>{item.content}</td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}

            <BaziCompatibilityAnalysis maleResult={maleResult} femaleResult={femaleResult} />

            <button
                style={{
                    marginTop: "20px",
                    padding: "10px 20px",
                    backgroundColor: "#1890ff",
                    color: "white",
                    border: "none",
                    borderRadius: "5px",
                    cursor: "pointer",
                    opacity: loadingAI ? 0.6 : 1
                }}
                onClick={handleShowDetails}
                disabled={loadingAI || (!maleResult || !femaleResult)}
            >
                {loadingAI ? "AI 分析中..." : "查看 AI 详情"}
            </button>

            {showDetails && aiAnalysisResult && (
                <div style={{ marginTop: "20px", padding: "20px", backgroundColor: "#f0f0f0", borderRadius: "12px" }}>
                    <h2 style={{ textAlign: "center", marginBottom: "20px", fontSize: "20px", fontWeight: "600" }}>AI 分析结果</h2>
                    <div 
                        style={{ 
                            fontSize: "16px", 
                            lineHeight: "1.8", 
                            color: "#444", 
                            whiteSpace: "pre-wrap" 
                        }}
                        dangerouslySetInnerHTML={{ 
                            __html: parseAIAnswer(aiAnalysisResult.answer) 
                        }}
                    />
                </div>
            )}
        </div>
    );
}

export default Index;    